package com.tanhua.dubbo.api;


import com.tanhua.domain.mongo.*;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.utils.IdService;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service
public class MovementApiImpl implements MovementApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveMovements(Movement movement) {
        Long userId = movement.getUserId(); //当前登录人的id
//假如当前登录人是张三  张三的好友是李四 王五
//                movement_friend_lisiID
//                movement_friend_wangwuId
//        1、补全默认值
        movement.setId(new ObjectId());
        movement.setCreated(new Date().getTime());
        movement.setPid(idService.getNextId("movement_detail")); //用于大数据推荐
//        2、保存详情 movement_detail
        mongoTemplate.save(movement);
//         3、保存到自己的相册集表中movement_mine_{ID}
        MovementMine movementMine = new MovementMine();
        movementMine.setCreated(new Date().getTime());
        movementMine.setMovementId(movement.getId());
        movementMine.setId(new ObjectId());
        mongoTemplate.save(movementMine,"movement_mine_"+userId); // movement_Mine_zhangsanId
//         4、查询当前登录人的好友  db.friend.find({userId:1})
        Query query = new Query(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

//        userId        friendId
//        zhangsanId      lisiId
//        zhangsanId      wangwuId
//        5、保存到自己的时间线表中movement_friend_{ID}
        for (Friend friend : friendList) {
            MovementFriend movementFriend = new MovementFriend();
            movementFriend.setId(new ObjectId());
            movementFriend.setCreated(new Date().getTime());
            movementFriend.setMovementId(movement.getId());
            movementFriend.setUserId(userId);
            mongoTemplate.save(movementFriend,"movement_friend_"+friend.getFriendId());
        }

        return movement.getId().toString();
    }

    @Override
    public PageResult queryFriendMovements(Long userId, Integer page, Integer pagesize) {
//        1、查询 movement_friend_USERID  db.movement_friend_USERID.find().sort({created:-1}).limit(10).skip( page-1 *pagesize )

        Query query = new Query();

        query.with(Sort.by(Sort.Direction.DESC,"created"));
        query.limit(pagesize).skip((page-1) *pagesize );
        List<MovementFriend> movementFriendList = mongoTemplate.find(query, MovementFriend.class, "movement_friend_" + userId);
        long count = mongoTemplate.count(query, MovementFriend.class, "movement_friend_" + userId);

//        2、查询movement_detail
        List<Movement> list = new ArrayList<>();
        for (MovementFriend movementFriend : movementFriendList) {
            ObjectId movementId = movementFriend.getMovementId();
            Movement movement = mongoTemplate.findById(movementId, Movement.class);
            if(movement!=null){
                list.add(movement);
            }

        }
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public PageResult queryRecommendMovements(Long userId, Integer page, Integer pagesize) {
//        1、分页查询推荐给当前登录人的动态
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        query.limit(pagesize).skip((page-1) *pagesize );
        List<RecommendMovement> recommendMovementList = mongoTemplate.find(query, RecommendMovement.class);
        long count = mongoTemplate.count(query, RecommendMovement.class);

        List<Movement> list = new ArrayList<>();
        for (RecommendMovement recommendMovement : recommendMovementList) {
            ObjectId movementId = recommendMovement.getMovementId();
            Movement movement = mongoTemplate.findById(movementId, Movement.class);
            if(movement!=null){
                list.add(movement);
            }
        }
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public PageResult queryMyselfMovements(Long userId, Integer page, Integer pagesize) {
        //        1、查询 movement_Mine_USERID  db.movement_Mine_USERID.find().sort({created:-1}).limit(10).skip( page-1 *pagesize )
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        query.limit(pagesize).skip((page-1) *pagesize );
        List<MovementMine> movementMineList = mongoTemplate.find(query, MovementMine.class, "movement_mine_" + userId);
        long count = mongoTemplate.count(query, MovementMine.class, "movement_mine_" + userId);
//        2、查询movement_detail
        List<Movement> list = new ArrayList<>();
        for (MovementMine movementMine : movementMineList) {
            ObjectId movementId = movementMine.getMovementId();
            Movement movement = mongoTemplate.findById(movementId, Movement.class);

            if(movement!=null&&movement.getState()==1){
                list.add(movement);
            }
        }
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public Movement queryMovementById(String movementId) {
        return mongoTemplate.findById(new ObjectId(movementId),Movement.class);

    }

    @Override
    public PageResult queryMovement(Integer page, Integer pagesize, Long userId, Integer state) {
        Query query = new Query();
        Criteria criteria = new Criteria();

        if(userId!=null){
            criteria.and("userId").is(userId);
        }
        if(state!=null){
            criteria.and("state").is(state);
        }
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        query.limit(pagesize).skip((page-1) *pagesize );

        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query, Movement.class);

        return new PageResult(page,pagesize,(int)count,movementList);
    }

    @Override
    public void updateStateById(String movementId, Integer state) {

        Query query = new Query(Criteria.where("id").is(new ObjectId(movementId)));

        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);

    }

    @Override
    public void passMovement(String[] movementIds) {
        Query query = new Query(Criteria.where("id").in(Arrays.asList(movementIds)));
        Update update = new Update();
        update.set("state",1);
        mongoTemplate.updateMulti(query,update,Movement.class);
    }
}